﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using com.freyr.protocol;
using g.txt;

public class Sw2aRewardListScript : MonoBehaviour
{
    public UIShowHideScript ShowHideEffect;
    public GameObject CloseButton;
    public UIGrid Grid;
    public UIScrollView ScrollView;
    public UISprite Frame;
    public UILabel Title;
    public Transform ItemDetialParent;
    public Camera Camera;
    public GameObject HeroLight;

    public UIClickToExitScript CancelPart;

    public GameObject LotteryButtonsObj;
    public GameObject DrawAgainBtn;
    public UILabel DrawAgainTimesLabel;
    public UISprite DrawAgainCostIcon;
    public UILabel DrawAgainCostLabel;
    public GameObject ConfirmBtn;

    public GameObject GrowthButtonsObj;
    public GameObject DoubleObject;
    public GameObject PromoteObject;
    public GameObject BuyDoubleBtn;

    //private List<ItemTemplateScript> mGiftObjs = new List<ItemTemplateScript>();
    private List<GameObject> mGiftObjs = new List<GameObject>();

    private const int S_SIZE_X = 525;
    private const int S_SIZE_Y = 328;
    private const int M_SIZE_X = 800;
    private const int M_SIZE_Y = 328;
    private const int L_SIZE_X = 800;
    private const int L_SIZE_Y = 525;
    private const int S_SIZE_Y_LOTTERY = 388;
    private const int S_SIZE_Y_GROWTH = 388;
    private const float SCROLL_Y_NORMAL = -33f;
    private const float SCROLL_Y_LOTTERY = 5f;
    private const float SCROLL_Y_GROWTH = 5f;
    private const float BUTTONS_Y_LOTTERY_ONE = -100f;
    private const float BUTTONS_Y_LOTTERY_TEN = -160f;
    private const float BUTTONS_Y_GROWTH = -100f;

    public delegate void VoidDelegate();
    private VoidDelegate CloseFunction;

    private bool mIsFromLottery = false;
    private bool mIsFromGrowthSupply = false;

    private int mHideState = 0;

    private List<PGift> mTempGiftList;

    void Awake()
    {
        UIEventListener.Get(CloseButton).onClick += OnCloseButtonClick;
        UIEventListener.Get(DrawAgainBtn).onClick += OnBtnClick;
        UIEventListener.Get(ConfirmBtn).onClick += OnBtnClick;
        UIEventListener.Get(BuyDoubleBtn).onClick += OnBtnClick;

        ShowHideEffect.onHided = OnHided;
    }

    void OnEnable()
    {
        mHideState = 0;
    }

    public void ShowItems(List<PGift> gifts, List<PChip> chipList = null)
    {
        mIsFromLottery = false;
        mIsFromGrowthSupply = false;

        this.gameObject.SetActive(true);
        for (int i = 0; i < mGiftObjs.Count; i++)
        {
            GameObject.DestroyImmediate(mGiftObjs[i]);
        }
        mGiftObjs.Clear();
        int chipIndex = 0;

        foreach (PGift pGift in gifts)
        {
            bool isChip = false;
            TXTFactory.TXTItem txtItem = null;
            if (pGift.type == (sbyte)EGiftType.ITEM)
            {
                txtItem = GTXTManager.GetInstance().GetData<GTXTStorageItem>().GetData(pGift.id);
                if (txtItem.type == (sbyte)ESw2AItemType.CHIP
                    || txtItem.type == (sbyte)ESw2AItemType.CHIP_LOOT_GROUP)
                {
                    isChip = true;
                }
            }
            if (isChip)
            {
                if (chipList.Count <= chipIndex)
                    continue;
                GameObject giftObj = Instantiate(ChipTemplateScript.Template);
                giftObj.SetActive(true);
                giftObj.transform.FrSetParent(Grid.transform);
                ChipTemplateScript giftScript = giftObj.GetComponent<ChipTemplateScript>();
                Dictionary<int, Chip> chipDic = GameApp.GetInstance().GetUserState().GetChipDic();
                int key = chipList[chipIndex].chipKey;
                Chip chip = null;
                if (chipDic.ContainsKey(key))
                {
                    chip = chipDic[key];
                }
                else
                {
                    continue;
                }
                giftScript.SetChip(chip);
                ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
                helperScritp.Init(giftScript, Camera, ItemDetialParent);
                helperScritp.SetInfo(chip);
                mGiftObjs.Add(giftObj);
                chipIndex++;
            }
            else
            {
                GameObject giftObj = Instantiate(ItemTemplateScript.Template);
                giftObj.SetActive(true);
                giftObj.transform.FrSetParent(Grid.transform);
                ItemTemplateScript giftScript = giftObj.GetComponent<ItemTemplateScript>();
                FreyrUtils.AddComponent<UIDragScrollView>(giftScript.SelectedFrame);
                giftScript.Init(pGift);
                ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
                helperScritp.Init(giftScript, Camera, ItemDetialParent);
                helperScritp.SetInfo(pGift);
                mGiftObjs.Add(giftObj);
            }
        }
        Resize();
        Grid.Reposition();
        ScrollView.ResetPosition();

        ModifyCamera(true);
        ShowHideEffect.Show();
    }
    public void ModifyCamera(bool isShowing)
    {
        if (IAPUIScript.mInstance != null && IAPUIScript.mInstance.gameObject.activeSelf)
        {
            if (isShowing)
            {
                Camera.depth = 93;
                Camera.gameObject.SetActive(false);
                Camera.gameObject.SetActive(true);
            }
            else
            {
                Camera.depth = 90;
                Camera.gameObject.SetActive(false);
                Camera.gameObject.SetActive(true);
            }
        }
    }
    public void ShowGrowthItems(List<PGift> gifts, List<PChip> chipList = null)
    {
        mIsFromLottery = false;
        mIsFromGrowthSupply = true;
        bool doubleApplied = GameApp.GetInstance().GetUserState().GetIapBuyNum(GrowthSupplyScript.DOUBLE_IAP_NAME) > 0;

        this.gameObject.SetActive(true);
        for (int i = 0; i < mGiftObjs.Count; i++)
        {
            GameObject.DestroyImmediate(mGiftObjs[i]);
        }
        mGiftObjs.Clear();
        int chipIndex = 0;

        foreach (PGift pGift in gifts)
        {
            bool isChip = false;
            TXTFactory.TXTItem txtItem = null;
            if (pGift.type == (sbyte)EGiftType.ITEM)
            {
                txtItem = GTXTManager.GetInstance().GetData<GTXTStorageItem>().GetData(pGift.id);
                if (txtItem.type == (sbyte)ESw2AItemType.CHIP
                    || txtItem.type == (sbyte)ESw2AItemType.CHIP_LOOT_GROUP)
                {
                    isChip = true;
                }
            }
            if (isChip)
            {
                if (chipList.Count <= chipIndex)
                    continue;
                GameObject giftObj = Instantiate(ChipTemplateScript.Template);
                giftObj.SetActive(true);
                giftObj.transform.FrSetParent(Grid.transform);
                ChipTemplateScript giftScript = giftObj.GetComponent<ChipTemplateScript>();
                Dictionary<int, Chip> chipDic = GameApp.GetInstance().GetUserState().GetChipDic();
                int key = chipList[chipIndex].chipKey;
                Chip chip = null;
                if (chipDic.ContainsKey(key))
                {
                    chip = chipDic[key];
                }
                else
                {
                    continue;
                }
                giftScript.SetChip(chip);
                ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
                helperScritp.Init(giftScript, Camera, ItemDetialParent);
                helperScritp.SetInfo(chip);
                mGiftObjs.Add(giftObj);
                chipIndex++;
            }
            else
            {
                GameObject giftObj = Instantiate(ItemTemplateScript.Template);
                giftObj.SetActive(true);
                giftObj.transform.FrSetParent(Grid.transform);
                ItemTemplateScript giftScript = giftObj.GetComponent<ItemTemplateScript>();
                FreyrUtils.AddComponent<UIDragScrollView>(giftScript.SelectedFrame);
                giftScript.Init(pGift);
                if (doubleApplied)
                {
                    giftScript.SetDouble();
                }
                ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
                helperScritp.Init(giftScript, Camera, ItemDetialParent);
                helperScritp.SetInfo(pGift);
                mGiftObjs.Add(giftObj);
            }
        }
        Resize();
        Grid.Reposition();
        ScrollView.ResetPosition();

        ShowHideEffect.Show();
    }

    public void ShowItem(EGiftType type, int num, short id = 0)
    {
        List<PGift> gifts = new List<PGift>();
        PGift gift = new PGift();
        gift.type = (sbyte)type;
        gift.id = id;
        gift.number = num;
        gifts.Add(gift);
        ShowItems(gifts);
    }

    public void ShowItems(List<PLottery> lotteryList) //Lottery专用
    {
        mIsFromLottery = true;
        mIsFromGrowthSupply = false;

        this.gameObject.SetActive(true);
        for (int i = 0; i < mGiftObjs.Count; i++)
        {
            GameObject.DestroyImmediate(mGiftObjs[i]);
        }
        mGiftObjs.Clear();

        if (lotteryList != null)
        {
            for (int i = 0; i < lotteryList.Count; i++)
            {
                if (lotteryList[i].type == 1)
                {
                    AddItem(ItemTemplateScript.Template, lotteryList[i]);
                }
                else if (lotteryList[i].type == 2)
                {
                    AddHero(HeroTemplateScript.Template, lotteryList[i]);
                }
            }
        }
        Resize();

        Grid.Reposition();

        ShowHideEffect.Show();
    }

    private void Resize()
    {
        if (mIsFromLottery)
        {
            LotteryButtonsObj.SetActive(true);
            GrowthButtonsObj.SetActive(false);
            ScrollView.transform.localPosition = new Vector3(0f, SCROLL_Y_LOTTERY, 0f);
            CancelPart.enabled = false;

            if (mGiftObjs.Count == 1)
            {
                Grid.cellWidth = 150;
                Grid.cellHeight = 180;
                Frame.width = S_SIZE_X;
                Frame.height = S_SIZE_Y_LOTTERY;

                LotteryButtonsObj.transform.localPosition = new Vector3(0f, BUTTONS_Y_LOTTERY_ONE, 0f);
                DrawAgainTimesLabel.text = LocalizationManager.GetInstance().GetString("LOC_BTN_RECRUIT_AGAIN_1");
                SetDrawCostInfo(false);
            }
            else
            {
                Grid.cellWidth = 120;
                Grid.cellHeight = 120;
                Frame.width = L_SIZE_X;
                Frame.height = L_SIZE_Y;

                LotteryButtonsObj.transform.localPosition = new Vector3(0f, BUTTONS_Y_LOTTERY_TEN, 0f);
                DrawAgainTimesLabel.text = LocalizationManager.GetInstance().GetString("LOC_BTN_RECRUIT_AGAIN_2");
                SetDrawCostInfo(true);
            }
        }
        else if (mIsFromGrowthSupply)
        {
            LotteryButtonsObj.SetActive(false);
            GrowthButtonsObj.SetActive(true);
            ScrollView.transform.localPosition = new Vector3(0f, SCROLL_Y_GROWTH, 0f);
            CancelPart.enabled = true;

            Grid.cellWidth = 150;
            Grid.cellHeight = 180;
            Frame.width = S_SIZE_X;
            Frame.height = S_SIZE_Y_GROWTH;

            GrowthButtonsObj.transform.localPosition = new Vector3(0f, BUTTONS_Y_GROWTH, 0f);
            bool doubleApplied = GameApp.GetInstance().GetUserState().GetIapBuyNum(GrowthSupplyScript.DOUBLE_IAP_NAME) > 0;
            PromoteObject.SetActive(!doubleApplied);
            DoubleObject.SetActive(doubleApplied);
        }
        else
        {
            LotteryButtonsObj.SetActive(false);
            GrowthButtonsObj.SetActive(false);
            ScrollView.transform.localPosition = new Vector3(0f, SCROLL_Y_NORMAL, 0f);
            CancelPart.enabled = true;

            if (mGiftObjs.Count <= 3)
            {
                Grid.cellWidth = 150;
                Grid.cellHeight = 180;
                Frame.width = S_SIZE_X;
                Frame.height = S_SIZE_Y;
            }
            else if (mGiftObjs.Count <= 5)
            {
                Grid.cellWidth = 120;
                Grid.cellHeight = 180;
                Frame.width = M_SIZE_X;
                Frame.height = M_SIZE_Y;
            }
            else
            {
                Grid.cellWidth = 120;
                Grid.cellHeight = 150;
                Frame.width = L_SIZE_X;
                Frame.height = L_SIZE_Y;
            }
            ScrollView.contentPivot = mGiftObjs.Count > 10 ? UIWidget.Pivot.Top : UIWidget.Pivot.Center;
        }
    }

    private void AddItem(GameObject ItemTemplate, PLottery pLottery)
    {
        PGift pGift = new PGift();
        pGift.type = pLottery.type;
        if (pLottery.type == 1)
        {
            pGift.type = (sbyte)EGiftType.ITEM;
        }
        else if (pLottery.type == 2)
        {
            pGift.type = (sbyte)EGiftType.HERO;
        }
        pGift.number = pLottery.itemNum;
        pGift.id = pLottery.itemId;
        GameObject giftObj = Instantiate(ItemTemplate);
        giftObj.SetActive(true);
        giftObj.transform.parent = Grid.transform;
        giftObj.transform.localPosition = Vector3.zero;
        giftObj.transform.localRotation = Quaternion.identity;
        giftObj.transform.localScale = new Vector3(1f, 1f, 1f);
        ItemTemplateScript giftScript = giftObj.GetComponent<ItemTemplateScript>();
        giftScript.Init(pGift);
        ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
        helperScritp.Init(giftScript, Camera, ItemDetialParent);
        helperScritp.SetInfo(pGift);
        mGiftObjs.Add(giftObj);
    }

    private void AddHero(GameObject HeroTemplate, PLottery pLottery)
    {
        GameObject giftObj = Instantiate(HeroTemplate);
        giftObj.SetActive(true);
        giftObj.transform.parent = Grid.transform;
        giftObj.transform.localPosition = Vector3.zero;
        giftObj.transform.localRotation = Quaternion.identity;
        giftObj.transform.localScale = new Vector3(1f, 1f, 1f);
        HeroTemplateScript giftScript = giftObj.GetComponent<HeroTemplateScript>();
        giftScript.Init(pLottery.itemId);
        ItemDetailHelperScript helperScritp = giftObj.AddComponent<ItemDetailHelperScript>();
        helperScritp.Init(giftScript, Camera, ItemDetialParent);
        helperScritp.SetInfo(pLottery.itemId);
        mGiftObjs.Add(giftObj);

        GameObject lightObj = GameObject.Instantiate(HeroLight);
        lightObj.transform.FrSetParent(giftObj.transform);
        lightObj.transform.localPosition = new Vector3(-5, 0, 0);
        UISprite sprite = lightObj.GetComponent<UISprite>();
        sprite.spriteName = "common_light_" + UIConstant.HERO_RANK_SPRITE_SUFFIX[giftScript.GetHeroInitRank()];
    }

    private void SetDrawCostInfo(bool isTen)
    {
        short ticketNum = LotteryManager.GetInctance().GetLotteryTicketNum();
        int ticketNeedNum = isTen ? 10 : 1;

        if (ticketNum >= ticketNeedNum)
        {
            DrawAgainCostIcon.spriteName = LotteryManager.GetInctance().GetLotteryTicketSpriteName();
            DrawAgainCostLabel.text = FreyrUtils.GetCostLabelText(ticketNum, ticketNeedNum);
        }
        else
        {
            short mithrilCostKey = isTen ? GlobalKey.MITHRIL_LOTTERY_10_MITHRIL : GlobalKey.MITHRIL_LOTTERY_1_MITHRIL;
            DrawAgainCostIcon.spriteName = UIConstant.NAME_WHOLE_RESOURCE_MITHRIL;
            DrawAgainCostLabel.text = SwGlobal.GlobalDataStorage.GetDataValue(mithrilCostKey).ToString();
        }
    }

    void OnCloseButtonClick(GameObject go)
    {
        ShowHideEffect.Hide();
    }

    private void OnBtnClick(GameObject go)
    {
        if (go == DrawAgainBtn)
        {
            mHideState = 1;
        }
        else if (go == BuyDoubleBtn)
        {
            IAPUIScript.ShowIAPUI(IAPUIScript.EPageType.MONTH_CARD);
        }

        ShowHideEffect.Hide();
    }

    private void OnHided()
    {
        if (CloseFunction != null)
        {
            CloseFunction();
        }

        if (mHideState == 1)
        {
            LotteryUIScript.mInstance.TryDrawManually(mGiftObjs.Count > 1);
        }
        ModifyCamera(false);
    }

    public void AddCloseFunction(VoidDelegate function)
    {
        CloseFunction += function;
    }

    public void RemoveCloseFunction(VoidDelegate function)
    {
        CloseFunction -= function;
    }

    public void SetTempGiftList(List<PGift> tempGiftList)
    {
        mTempGiftList = tempGiftList;
    }

    public List<PGift> GetTempGiftList()
    {
        return mTempGiftList;
    }
}
